using System.Linq;
using Microsoft.EntityFrameworkCore;
using MvcDemo.Db;
using MvcDemo.Models;

namespace MvcDemo.Repository
{
    public class EfRepository<T> : IRepository<T> where T : Pro
    {
        private readonly Dbsoft _Db;
        private readonly DbSet<T> _table;
        public EfRepository(){
            _Db=new Dbsoft();
            _table=_Db.Set<T>();
        }
        public IQueryable<T> Table {
            get{
                return _table as IQueryable<T>;
            }
        }

        public void Delect(int id)
        {
            var entity = _table.Where(x=>x.id==id).FirstOrDefault();
            entity.IsDeleted=true;
            entity.UpdatedTime=System.DateTime.Now;
            _table.Update(entity);
            _Db.SaveChanges();
        }

        public T GetById(int id)
        {
            var entity = _table.Where(x=>x.id==id).FirstOrDefault();
            return entity;
        }

        public void Insert(T entity)
        {
            entity.CreatedTime=System.DateTime.Now;
            entity.UpdatedTime=System.DateTime.Now;
            _table.Add(entity);
            _Db.SaveChanges();
        }

        public void Update(T entity)
        {
            entity.UpdatedTime=System.DateTime.Now;
            _table.Update(entity);
            _Db.SaveChanges();
        }
    }
}